package org.je.database.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author fanyifeng 2012-10-16 上午10:27:04
 */
public class DBConnection
{
	private Connection	con;
	private Statement	st;
	final DataSource	ds;

	public DBConnection(DataSource ds) {
		if (ds == null) {
			throw new NullPointerException("datasource-is-null");
		}
		this.ds = ds;
	}

	Statement statement() {
		if (st == null) {
			this.reconnect();
		}
		return st;
	}

	void reconnect() {
		System.out.println("connect : " + ds.connectionString);
		long d = System.nanoTime();
		if (st != null || con != null) {
			close();
		}
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			throw new RuntimeException("class-not-found-error ", e);
		}
		try {
			con = DriverManager.getConnection(ds.connectionString, ds.user, ds.pwd);
			con.setAutoCommit(false);
			con.setTransactionIsolation(ds.connectionLevel);
		} catch (SQLException e) {
			throw new RuntimeException("create-connection-error ", e);
		}

		try {
			st = con.createStatement();
		} catch (SQLException e) {
			close();
			throw new RuntimeException("create-statement-error ", e);
		}

		System.out.println("connet use time " + (System.nanoTime() - d) / 1000000 + " millis");
	}

	boolean commit() {
		try {
			con.commit();
			return true;
		} catch (Exception ex) {
			return false;
		}
	}

	boolean rollback() {
		try {
			con.rollback();
			return true;
		} catch (Exception ex) {
			return false;
		}
	}

	private void close() {
		try {
			st.close();
		} catch (Exception e) {}
		try {
			con.close();
		} catch (Exception e) {}
	}

}
